package com.lzy.cloud.search.client.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lzy.cloud.search.client.service.MultiSearchService;
import com.lzy.cloud.search.client.util.EsClient;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 在同一API中执行多个搜索请求
 */
@Service
public class MultiSearchServiceImpl implements MultiSearchService {

    @Autowired
    private EsClient client;

    public void multiSearch()   {

        SearchRequestBuilder srb1 = client.getConnection()
                .prepareSearch().setQuery(QueryBuilders.queryStringQuery("elasticsearch")).setSize(1);

        SearchRequestBuilder srb2 = client.getConnection()
                .prepareSearch().setQuery(QueryBuilders.matchQuery("name", "kimchy")).setSize(1);

        MultiSearchResponse sr = client.getConnection().prepareMultiSearch()
                .add(srb1)
                .add(srb2)
                .get();

        // You will get all individual responses from MultiSearchResponse#getResponses()
        long nbHits = 0;
        for (MultiSearchResponse.Item item : sr.getResponses()) {
            SearchResponse response = item.getResponse();

            nbHits += response.getHits().getTotalHits();

           //打印
            SearchHit[] searchHits = response.getHits().getHits();
            for (SearchHit searchHit : searchHits) {
                System.out.println(JSON.toJSONString(searchHit.getSourceAsString(), SerializerFeature.PrettyFormat));
            }
        }

        System.out.println("nbHits:" + nbHits);

    }

}
